$(function () {
    var defaultColunms = BaseTable.initColumn();
    var table = new BSTable(BaseTable.id, "/sys/user/list", defaultColunms);
    table.setPaginationType("server");
    BaseTable.table = table.init();
    init();
});

/**
 * 表格类容初始化
 */
var BaseTable = {
    id: "table",	//表格id
    seItem: null,		//选中的条目
    table: null,
};

/**
 * 初始化表格的列
 */
BaseTable.initColumn = function () {
    return [
        {field: 'selectItem',checkbox : true},
        {field: 'id',title : '序号',align: 'center', valign: 'middle',formatter : function(value, row, index) {return index+1;}},
        {title: 'id', field: 'id', visible: false, align: 'center', valign: 'middle'},
        {title: '用户ID', field: 'userId', align: 'center', valign: 'middle', sortable: true},
        {title: '用户名', field: 'username', align: 'center', valign: 'middle', sortable: true},
        {title: '手机号', field: 'mobile', align: 'center', valign: 'middle', sortable: true},
        {title: '状态', field: 'status', align: 'center', valign: 'middle', sortable: true,formatter: function(value, row, index){
            return value === 0 ?
                '<span class="label label-danger">禁用</span>' :
                '<span class="label label-success">正常</span>';
        }},
        {title: '创建时间', field: 'createTime', align: 'center', valign: 'middle', sortable: true},
        {title: '操作', field: 'status', align: 'center', valign: 'middle', sortable: true,formatter: function(value, row, index){
            var d = '<a class="btn btn-danger " href="#" onclick="remove('+row.userId+')"><i class="fa fa-trash-o">删除</i></a>';
            var e = '&nbsp;&nbsp;&nbsp;&nbsp;';
            var f = '<a class="btn btn-primary " href="#" onclick="getInfo(' + row.userId + ')"><i class="fa fa-pencil-square-o">详情</i>';
            return d+e+f;
        }}
    ];
};

/**
 * 检查是否选中
 */
BaseTable.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        alert("请先选中表格中的某一记录！");
        return false;
    } else {
        BaseTable.seItem = selected[0];
        return true;
    }
};


/**
 * 查询表格列表
 */
BaseTable.search = function () {
    var queryData = {};
    queryData['username'] = $("#username").val();
    BaseTable.table.refresh({query: queryData});
};

function remove(id) {
    var ids = new Array();
    ids.push(id);
    ajaxSubmit("/sys/user/delete", JSON.stringify(ids), function (r) {
        if (r.code === 0) {
            showSuccessMsg("操作成功！",function () {
                reloadPage();
            });
        } else {
            alert(r.msg);
        }
    })
}

function clearInput(obj) {
    $(obj).prev().val('');
}

function getInfo(id) {
    vm.getUser(id);
    //获取角色信息
    vm.getRoleList();
    vm.showList = false;
}

var vm = new Vue({
    el:'#app',
    data:{
        showList: true,
        roleList:{},
        data:{
            status:1,
            roleIdList:[]
        },
        username:''
    },
    methods: {
        add: function(){
            vm.roleList = {};
            vm.data = {status:1,roleIdList:[]};
            //获取角色信息
            this.getRoleList();
            vm.showList = false;
        },
        del: function () {
        	//获取选中的列
            var ids = getSelections('table', 'userId');
            if (ids.length == 0) {
                alert('请选择需要删除的数据！');
                return;
            }
            console.info(ids);
            showWarningMsg('确定要删除选中的记录？',function () {
				ajaxSubmit('/sys/user/delete',JSON.stringify(ids),function (r) {
                    if(r.code == 0){
                        showSuccessMsg('操作成功!');
                        vm.reload();
                    }else{
                        alert(r.msg);
                    }
                })
            })
        },
        saveOrUpdate: function () {
            var url = vm.data.userId == null ? "sys/user/save" : "sys/user/update";
            ajaxSubmit(baseURL + url,JSON.stringify(vm.data),function (r) {
                if(r.code == 0){
                    showSuccessMsg('操作成功!');
                    vm.reload();
                }else{
                    alert(r.msg);
                }
            })
        },
        getUser: function(userId){
            $.get(baseURL + "sys/user/info/"+userId, function(r){
                vm.data = r.user;
                vm.data.password = null;
                vm.username = vm.data.username;
            });
        },
        getRoleList: function(){
            $.get(baseURL + "sys/role/select", function(r){
                vm.roleList = r.list;
            });
        },
        reload: function () {
            resetForm();
            vm.showList = true;
            BaseTable.search();
        }
    }
});

function init() {
    $("#Form")
        .bootstrapValidator(
            {
                errorElement: 'span',
                errorClass: 'help-block',
                fields: {
                    username: {
                        validators: {
                            notEmpty: {
                                message: '该项目不能为空'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z\d]+$/,
                                message: '该项目的格式为数字或英文字母'
                            },
                            stringLength: {
                                min: 6,
                                max: 20,
                                message: '账号长度在6到16之间'
                            },
                            remote: {
                                message: '该用户账号已存在',
                                url: '/common/checkUserName',
                                data: function(validator) {
                                    if (vm.data!=null && vm.username == $('[name="username"]').val()) {
                                        return false;
                                    }
                                    return {
                                        username: vm.data.username,
                                    };
                                },
                            }
                        }
                    },
                    email: {
                        validators: {
                            // notEmpty: {
                            //     message: '邮件不能为空'
                            // },
                            emailAddress: {
                                message: '请输入正确的邮件地址如：123@qq.com'
                            },
                            stringLength: {
                                min: 5,
                                max: 30,
                                message: '最大长度不能超过30位'
                            },
                        }
                    },
                    mobile: {
                        validators: {
                            // notEmpty: {
                            //     message: '请输入手机号码'
                            // },
                            regexp: {
                                regexp: /^(10[0-9]|13[0-9]|14[1456789]|15[0-3,5-9]|16[6]|17[01235678]|18[0-9]|19[89])\d{8}$/,
                                message: '手机号码输入有误'
                            },
                            stringLength: {
                                min: 11,
                                max: 11,
                                message: '请输入11位手机号码'
                            },
                        }
                    },
                    password: {
                        validators: {
                            notEmpty: {
                                message: '该项目不能为空'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z\d]+$/,
                                message: '该项目的格式为数字或英文字母'
                            },
                            stringLength: {
                                min: 6,
                                max: 20,
                                message: '密码长度在6到16之间'
                            },
                        }
                    },
                    repeatPwd: {
                        validators: {
                            notEmpty: {
                                message: '该项目不能为空'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z\d]+$/,
                                message: '该项目的格式为数字或英文字母'
                            },
                            identical: {//与指定控件内容比较是否相同，比如两次密码不一致
                                field: 'password',//指定控件name
                                message: '两次密码输入的内容不一致'
                            },
                            stringLength: {
                                min: 6,
                                max: 20,
                                message: '密码长度在6到16之间'
                            },
                        }
                    },
                    status:{
                        validators: {
                            notEmpty: {
                                message: '该项目不能为空'
                            },
                        }
                    }
                }
            }).on('success.form.bv', function (e) {
        e.preventDefault();
        vm.saveOrUpdate();
        return false;
    });
}